/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

namespace Oceanside
{
    /// <summary>
    /// 
    /// </summary>
    public partial class PagePrintersImp : PageImpBaseClass
    {
        ListView listviewChosenPrinters;
        ListView listviewAvailablePrinters;
        ComboBox comboBoxGroupsName;
        ComboBox comboBoxExistingPrinters;

        Button buttonAddSelectedPrinters;
        Button buttonRemoveSelectedPrinters;
        DbLinkedTextBox tbPrinterPath;
        DbLinkedTextBox tbPrinterManufacturer;
        DbLinkedTextBox tbPrinterModel;

        /// Constructor
        /// </summary>
        public PagePrintersImp(
            ListView listviewChosenPrinters,
            ListView listviewAvailablePrinters,
            UIElementCollection uielementsChildren,
            ComboBox comboBoxGroupsName,
            ComboBox comboBoxExistingPrinters,
            DbLinkedTextBox textBoxGroupName,
            DbLinkedTextBox tbPrinterName,
            DbLinkedTextBox tbPrinterPath,
            DbLinkedTextBox tbPrinterManufacturer,
            DbLinkedTextBox tbPrinterModel,
            Button buttonAddSelectedPrinters,
            Button buttonRemoveSelectedPrinters,
            Button bAssignPManufacturer,
            Button bAssignPrinterModel,
            Button bAssignPrinterPath,
            GroupBox pEntityGroupBox,
            GroupBox pGroupsGroupBox)
            : base()
        {
            this.ButtonNumber = "6";
            this.ButtonLabelText = "Printers";
            mButtonDeleteEntityName = "Delete Printer";
            mButtonNewEntityName = "New Printer";
            mButtonNewGroupName = "New Printer Group";
            mButtonDeleteGroupName = "Delete Printer Group";

            this.tbPrinterPath = tbPrinterPath;
            this.tbPrinterManufacturer = tbPrinterManufacturer;
            this.tbPrinterModel = tbPrinterModel;
            this.tbPrinterPath = tbPrinterPath;

            RegisterSaveMeGroupBoxes(pGroupsGroupBox, pEntityGroupBox);

            this.listviewAvailablePrinters = listviewAvailablePrinters;
            this.listviewChosenPrinters = listviewChosenPrinters;

            this.comboBoxGroupsName = comboBoxGroupsName;
            this.comboBoxExistingPrinters = comboBoxExistingPrinters;

            this.buttonAddSelectedPrinters = buttonAddSelectedPrinters;
            this.buttonRemoveSelectedPrinters = buttonRemoveSelectedPrinters;

            mTextBoxesList.Add(tbPrinterModel);
            mTextBoxesList.Add(textBoxGroupName);
            mTextBoxesList.Add(tbPrinterName);
            mTextBoxesList.Add(tbPrinterPath);
            mTextBoxesList.Add(tbPrinterManufacturer);


            RegisterListview(listviewAvailablePrinters);
            RegisterListview(listviewChosenPrinters);
            RegisterUiElementsList(uielementsChildren);

            ListofComboboxes.Add(comboBoxGroupsName);
            ListofComboboxes.Add(comboBoxExistingPrinters);

            listviewAvailablePrinters.SelectionChanged
                += new SelectionChangedEventHandler(listviewAvailablePrinters_SelectionChanged_NOTHROW);
            listviewChosenPrinters.SelectionChanged
                += new SelectionChangedEventHandler(listviewAvailablePrinters_SelectionChanged_NOTHROW);


            mListOfControlsToHideInNonEditMode.Add(buttonAddSelectedPrinters);
            mListOfControlsToHideInNonEditMode.Add(buttonRemoveSelectedPrinters);

            mListOfControlsToHideInNonEditMode.Add(bAssignPManufacturer);
            mListOfControlsToHideInNonEditMode.Add(bAssignPrinterModel);
            mListOfControlsToHideInNonEditMode.Add(bAssignPrinterPath);

            bAssignPManufacturer.Click += new RoutedEventHandler(bAssignPManufacturer_Click);
            bAssignPrinterModel.Click += new RoutedEventHandler(bAssignPrinterModel_Click);
            bAssignPrinterPath.Click += new RoutedEventHandler(bAssignPrinterPath_Click);

            buttonAddSelectedPrinters.Click += new RoutedEventHandler(buttonAddSelectedPrinters_Click);
            buttonRemoveSelectedPrinters.Click += new RoutedEventHandler(buttonRemSelectedPrinters_Click);

            ///If the selection changes lock the form down.
            comboBoxGroupsName.SelectionChanged += new SelectionChangedEventHandler(comboBoxGroupsName_SelectionChanged);


            mEntityAddDeleteLoggingEnabled = true;

        }

        void bAssignPrinterPath_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<string> sharedNetPrinters = PrintSpool.GetAllPrinterNames();
                sharedNetPrinters.Insert(0, "Not Assigned");
                RedirectPrinterOutput rpo = new RedirectPrinterOutput(sharedNetPrinters);
                rpo.SetMessage("The list below should include all printers that have been installed on your the local KIOSK as well as the print server.  Please select a printer path from the list.");
                rpo.ShowDialog();
                if (RedirectPrinterOutput.LastResponse != UserResponse.EXIT)
                {
                    tbPrinterPath.Text = RedirectPrinterOutput.LastRedirectPrinter;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        void bAssignPrinterModel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<string> modelList = new List<string>();
                modelList.Add("Not Assigned");
                modelList.Add("TM-T88V Thermal");
                modelList.Add("TM-U220B Impact");

                StringSelectionListBox sslb = new StringSelectionListBox(modelList);
                sslb.SetMessage("Please select a supported printer model from the list.");
                sslb.ShowDialog();
                if (StringSelectionListBox.LastResponse != UserResponse.EXIT)
                {
                    tbPrinterModel.Text = StringSelectionListBox.ChosenString;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        void bAssignPManufacturer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<string> manufactList = new List<string>();
                manufactList.Add("Epson");
                StringSelectionListBox sslb = new StringSelectionListBox(manufactList);
                sslb.SetMessage("Please select a supported printer manufacturer from the list.  Oceanside only supports printers that we feel outperform the normal industry standards.");
                sslb.ShowDialog();
                if (StringSelectionListBox.LastResponse != UserResponse.EXIT)
                {
                    tbPrinterManufacturer.Text = StringSelectionListBox.ChosenString;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetGroupObjectSet()
        {
            try
            {
                var q = from PG in Context.PRINTER_GROUPS where PG.IsDeleted == false select PG;
                if (q.Any())
                {
                    return new List<EntityObject>(q.ToList());
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetEntityObjectSet()
        {
            try
            {
                var q = from P in Context.PRINTERS where P.IsDeleted == false select P;
                if (q.Any())
                {
                    return new List<EntityObject>(q.ToList());
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void comboBoxGroupsName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateListViews();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listviewAvailablePrinters_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (this.IsEditableMode())
                {
                    ListView lv = sender as ListView;
                    if (lv == listviewAvailablePrinters)
                    {
                        if (lv.SelectedItems.Count != 0)
                        {
                            buttonAddSelectedPrinters.IsEnabled = true;
                        }
                        else
                        {
                            buttonAddSelectedPrinters.IsEnabled = false;
                        }
                    }
                    else if (lv == listviewChosenPrinters)
                    {
                        if (lv.SelectedItems.Count != 0)
                        {
                            buttonRemoveSelectedPrinters.IsEnabled = true;
                        }
                        else
                        {
                            buttonRemoveSelectedPrinters.IsEnabled = false;
                        }
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PAGEFORMODGR_LISTVIEW_SELECTION_CHANGE, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void ResetFocus()
        {
            base.ResetFocus();
            buttonRemoveSelectedPrinters.IsEnabled = false;
            buttonAddSelectedPrinters.IsEnabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddSelectedPrinters_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                PRINTER_GROUP pgroup = comboBoxGroupsName.SelectedItem as PRINTER_GROUP;
                if (pgroup != null)
                {
                    foreach (object prodMod in listviewAvailablePrinters.SelectedItems)
                    {
                        pgroup.PRINTERS.Add(prodMod as PRINTER);
                    }
                    UpdateListViews();
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRemSelectedPrinters_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                PRINTER_GROUP pgroup = comboBoxGroupsName.SelectedItem as PRINTER_GROUP;
                if (pgroup != null)
                {
                    foreach (object printer in listviewChosenPrinters.SelectedItems)
                    {
                        pgroup.PRINTERS.Remove(printer as PRINTER);
                    }
                }
                UpdateListViews();
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        private void UpdateListViews()
        {
            PRINTER_GROUP pgroup = comboBoxGroupsName.SelectedItem as PRINTER_GROUP;
            if (pgroup != null)
            {
                List<PRINTER> printers = new List<PRINTER>();
                var qAvailable = from PR in Context.PRINTERS
                                 where PR.IsDeleted == false &&
                                 PR.IsProductGroupPrinter == true
                                 orderby PR.Name
                                 select PR;

                List<PRINTER> usedList = null;
                if (qAvailable.Any())
                {
                    usedList = pgroup.PRINTERS.ToList();
                    foreach (PRINTER p in qAvailable)
                    {
                        if (!usedList.Contains(p))
                        {
                            printers.Add(p);
                        }
                    }
                }

                listviewAvailablePrinters.ItemsSource = printers;
                listviewChosenPrinters.ItemsSource = usedList;
            }
            else
            {
                listviewAvailablePrinters.ItemsSource = null;
                listviewChosenPrinters.ItemsSource = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedGroupObject()
        {
            PRINTER_GROUP selected = comboBoxGroupsName.SelectedItem as PRINTER_GROUP;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedEntityObject()
        {
            PRINTER selected = comboBoxExistingPrinters.SelectedItem as PRINTER;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        public override void MarkGroupDeleted()
        {
            PRINTER_GROUP selected = comboBoxGroupsName.SelectedItem as PRINTER_GROUP;
            if (selected != null)
            {
                selected.IsDeleted = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void MarkEntityDeleted()
        {
            PRINTER selected = comboBoxExistingPrinters.SelectedItem as PRINTER;
            if (selected != null)
            {
                selected.IsDeleted = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersGroupSource()
        {
            try
            {
                ///Create the query object.
                var query = from PG in
                                Context.PRINTER_GROUPS
                            where PG.IsDeleted == false
                            orderby PG.Name
                            select PG;

                if (query.Any())
                {
                    List<PRINTER_GROUP> list = query.ToList();
                    comboBoxGroupsName.ItemsSource = list;
                    if (list != null && list.Count != 0)
                    {
                        comboBoxGroupsName.SelectedItem = list.First();
                    }
                    else
                    {
                        comboBoxGroupsName.ItemsSource = null;
                    }
                }
                else
                {
                    comboBoxGroupsName.ItemsSource = null;
                }
                UpdateListViews();
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersEntitySource()
        {
            try
            {
                ///Create the query object.
                var query = from P in
                                Context.PRINTERS
                            where P.IsDeleted == false
                            orderby P.Name
                            select P;

                if (query.Any())
                {
                    List<PRINTER> list = query.ToList();
                    comboBoxExistingPrinters.ItemsSource = list;
                    if (list != null && list.Count != 0)
                    {
                        comboBoxExistingPrinters.SelectedItem = list.First();
                    }
                    else
                    {
                        comboBoxExistingPrinters.ItemsSource = null;
                    }
                }
                else
                {
                    comboBoxExistingPrinters.ItemsSource = null;
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject AddNewGroupObject()
        {
            PRINTER_GROUP newObject = null;
            try
            {
                var q = from PG in Context.PRINTER_GROUPS
                        where PG.Name.Equals("Not Assigned")
                        select PG;

                if (q.Count() == 0)
                {
                    newObject = new PRINTER_GROUP();
                    newObject.Name = "Not Assigned";
                    Context.PRINTER_GROUPS.AddObject(newObject);
                }
                else
                {
                    newObject = q.First();
                    if (newObject.IsDeleted)
                    {
                        newObject.IsDeleted = false;
                    }
                }
            }
            catch { }
            return newObject;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject AddNewEntityObject()
        {
            PRINTER newObject = null;
            try
            {
                var q = from P in Context.PRINTERS
                        where P.Name.Equals("Not Assigned")
                        select P;

                if (q.Count() == 0)
                {
                    newObject = new PRINTER();
                    newObject.Name = "Not Assigned";
                    Context.PRINTERS.AddObject(newObject);
                }
                else
                {
                    newObject = q.First();
                    if (newObject.IsDeleted)
                    {
                        newObject.IsDeleted = false;
                    }
                }
            }
            catch { }
            return newObject;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetGroupComboBox()
        {
            return comboBoxGroupsName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetEntityComboBox()
        {
            return comboBoxExistingPrinters;
        }
    }
}
